package com.joinway.framework.core.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.joinway.framework.core.repository.SystemConfigRepository;
import com.joinway.framework.extension.utils.NumberUtils;

@Component
public class FrameworkHelper implements ApplicationContextAware {

	private final static Logger log = LoggerFactory.getLogger(FrameworkHelper.class);
			
	static ApplicationContext ctx;
	
	static EnvConfig defaultEnvConfig = new EnvConfig();
	
	public static HttpServletRequest getHttpServletRequest(){
		ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		return attributes == null ? null : attributes.getRequest();
	}
	
	public static HttpServletResponse getHttpServletResponse(){
		ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		return attributes == null ? null : attributes.getResponse();
	}
	
	public static<T> T getBean(Class<T> type){
		T bean = null;
		
		try{
			bean = ctx.getBean(type);
		}catch(Exception e){
			log.warn("get bean " + type.getCanonicalName() + " failed", e.getMessage());
		}
		
		return bean;
	}
	
	public static<T> T getBean(String name, Class<T> type){
		T bean = null;
		
		try{
			bean = ctx.getBean(name, type);
		}catch(Exception e){
			log.warn("get bean " + type.getCanonicalName() + " failed", e.getMessage());
		}
		
		return bean;
	}
	
	public static String getAppNamePath(){
		return getHttpServletRequest().getContextPath();
	}
	
	public static String getAppServerRoot(){
		HttpServletRequest request = getHttpServletRequest();
		return StringUtils.join(new Object[] { request.getScheme(),
				"://", request.getServerName(), ":", request.getServerPort(),
				request.getContextPath(), "/" });
	}
	
	public static String getAppRootLocalPath(){
		return getHttpServletRequest().getServletContext().getRealPath("/");
	}
	
	public static String getWebServerRoot() throws Exception {
		return getWebServerRoot(null);
	}
	
	public static String getWebServerRoot(Integer port) throws Exception {
		HttpServletRequest request = getHttpServletRequest();
		
		String root;
		int wport = port;
		
		SystemConfigRepository config = getBean(SystemConfigRepository.class);
		
		do{
			if(port != null && port != 0){
				wport = port;
				break;
			}
			
			wport = NumberUtils.convertToInt(System.getProperty(SystemConfigRepository.AdminHostPort));
			if(wport > 0) break;
			
			if(config != null){
				wport = config.getIntValue(SystemConfigRepository.AdminHostPort);
			}
		}while(false);
		
		do{
			root = System.getProperty(SystemConfigRepository.AdminHostName);
			if(StringUtils.isNotBlank(root)) break;
			
			if(config != null){
				root = config.getStringValue(SystemConfigRepository.AdminHostName);
			}
			
			if(StringUtils.isNotBlank(root)) break;
			
			root = StringUtils.join(request.getScheme(), "://", request.getServerName());
			
		}while(false);
		
		boolean endWithSlash = false;
		if(root.endsWith("/")){
			root = root.substring(0, root.length() - 1);
			endWithSlash = true;
		}
		
		if(wport != 80){
			root = StringUtils.join(root, ":" + wport);
		}

		if(endWithSlash){
			root += "/";
		}
		
		return root;
	}

	public static String getOsName(){
		return System.getProperty("os.name");
	}
	
	public static String getPathSeparator(){
		return System.getProperty("path.separator");
	}
	
	public static EnvConfig getEnvCofnig(){
		EnvConfig config = getBean(EnvConfig.class);
		
		return config == null ? defaultEnvConfig : config;
	}
	
	public static String getRemoteIP(){
		EnvConfig config = getEnvCofnig();
		
		HttpServletRequest request = getHttpServletRequest();
		
		String remoteIP = "";
		
		do{
			if(config.isxForwardedForEnabled()){
				String ips = (String)request.getAttribute(config.getxForwardedForKey());
				
				if(StringUtils.isNotBlank(ips)){
					remoteIP = StringUtils.split(ips, ",")[0];
				}
				
				if(StringUtils.isNotBlank(remoteIP)) break;
			}
			
			if(config.isxRealIPEnabled()){
				remoteIP = (String)request.getAttribute(config.getxRealIPKey());
				
				if(StringUtils.isNotBlank(remoteIP)) break;
			}
			
			remoteIP = request.getRemoteAddr();
		}while(false);
		
		
		return remoteIP;
	}
	
	public static List<String> getHostIps() throws UnknownHostException {
		List<String> ips = new ArrayList<>();
		
		InetAddress[] ias = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
		
		if(ArrayUtils.isNotEmpty(ias)){
			for(InetAddress ia : ias){
				ips.add(ia.getHostAddress());
			}
		}
			
		return ips;
		
	}
	
//	public static<T> List<T> getSubClassList(Class<T> type){
//		ClassUtils.
//	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ctx = applicationContext;
	}
}
